package main.generator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class ClassTranslationParser {

  public static List<ClassTranslation> parse(String fileName) throws FileNotFoundException,
      XMLStreamException {
    List<ClassTranslation> classes = null;
    List<Translation> packages = new ArrayList<Translation>();
    ClassTranslation classTranslation = null;

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream(new File(fileName)));

    while (reader.hasNext()) {
      int Event = reader.next();

      switch (Event) {
        case XMLStreamConstants.START_ELEMENT: {
          switch (reader.getLocalName()) {
            case "translation":
              classes = new ArrayList<>();
              break;
            case "package":
              packages.add(new Translation(reader.getAttributeValue(0), reader
                  .getAttributeValue(1)));
              break;
            case "class":
              classTranslation = new ClassTranslation();
              classTranslation.setClassName(new Translation(reader.getAttributeValue(0), reader
                  .getAttributeValue(1)));
              classTranslation.setPackages(new ArrayList<>(packages));
              classTranslation.setMethods(new HashMap<String, String>());
              break;
            case "method":
              classTranslation.getMethods().put(reader.getAttributeValue(0), reader
                  .getAttributeValue(1));
          }
          break;
        }
        case XMLStreamConstants.END_ELEMENT: {
          switch (reader.getLocalName()) {
            case "class":
              classes.add(classTranslation);
              break;
          }
          break;
        }
      }
    }
    return classes;
  }
}
